package com.tatada.mvvmdemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.annotation.SuppressLint;
import android.os.Bundle;

import com.google.android.material.tabs.TabLayout;
import com.tatada.mvvmdemo.beans.TitleListBean;
import com.tatada.mvvmdemo.net.Net;
import com.tatada.mvvmdemo.net.TestNetApi;
import com.toshi.netlib.base.BaseObserver;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ViewPager vp;
    private TabLayout tab;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        vp = findViewById(R.id.vp);
        tab = findViewById(R.id.tab);

        getTab();
    }

    @SuppressLint("CheckResult")
    private void getTab() {
        TestNetApi.getService(Net.class).getTitleList().compose(TestNetApi.getInstance().applySchedulers(new BaseObserver<TitleListBean>() {
            @Override
            public void onSuccess(TitleListBean listBean) {
                if (listBean.getData() != null && listBean.getData().size() > 0) {
                    String[] strList = new String[listBean.getData().size()];
                    List<Fragment> fragments = new ArrayList<>();
                    for (int i = 0; i < listBean.getData().size(); i++) {
                        strList[i] = listBean.getData().get(i).getTitle();
                        fragments.add(NewsFragment.obtain(listBean.getData().get(i).getId()));
                    }
                    vp.setOffscreenPageLimit(5);
                    vp.setAdapter(new VPAdapter(getSupportFragmentManager(), fragments, strList));
                    tab.setupWithViewPager(vp);
                }
            }

            @Override
            public void onFailure(Throwable e) {

            }
        }));
    }

}
